package com.benefm.multipar.pad.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import com.benefm.multipar.pad.R;

public class CircularGaugeView extends View {

    // 定义变量
    private Paint backgroundPaint, coloredArcPaint, scalePaint, textPaint, valuePaint, heartPaint, wavePaint;
    private Path heartPath, wavePath;
    private RectF arcRect;
    private int width, height;
    private float centerX, centerY;
    private float radius;

    // 配置参数
    private float startAngle = 0f;
    private float sweepAngle = 360f;
    private float maxValue = 100f;
    private float currentValue = 82f; // 默认值
    private int normalColor = Color.parseColor("#1E88E5"); // 蓝色
    private int warningColor = Color.parseColor("#F44336"); // 红色
    private int criticalThreshold = 80; // 警告阈值
    private String title = "OXYGEN";
    private String unit = "%";
    private int[] scales = {10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100}; // 刻度值

    public CircularGaugeView(Context context) {
        super(context);
        init(null);
    }

    public CircularGaugeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        // 解析自定义属性
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.BloodOxygenDashboard);
            normalColor = a.getColor(R.styleable.BloodOxygenDashboard_normalColor, normalColor);
            warningColor = a.getColor(R.styleable.BloodOxygenDashboard_warningColor, warningColor);
            criticalThreshold = a.getInt(R.styleable.BloodOxygenDashboard_criticalThreshold, criticalThreshold);
            title = a.getString(R.styleable.BloodOxygenDashboard_title);
            if (title == null) title = "OXYGEN";
            unit = a.getString(R.styleable.BloodOxygenDashboard_unit);
            if (unit == null) unit = "%";
            a.recycle();
        }

        // 背景弧线画笔
        backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        backgroundPaint.setStyle(Paint.Style.STROKE);
        backgroundPaint.setStrokeWidth(26f);
        backgroundPaint.setColor(Color.parseColor("#37474F"));
        backgroundPaint.setStrokeCap(Paint.Cap.ROUND);

        // 彩色弧线画笔
        coloredArcPaint = new Paint(backgroundPaint);

        // 刻度线画笔
        scalePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        scalePaint.setStrokeWidth(4f);
        scalePaint.setColor(Color.WHITE);
        scalePaint.setStrokeCap(Paint.Cap.ROUND);

        // 刻度文字画笔
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(24f);
        textPaint.setColor(Color.parseColor("#B0BEC5"));
        textPaint.setTextAlign(Paint.Align.CENTER);

        // 主数值画笔
        valuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        valuePaint.setTextSize(48f);
        valuePaint.setColor(Color.WHITE);
        valuePaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
        valuePaint.setTextAlign(Paint.Align.CENTER);

        // 心形画笔
        heartPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        heartPaint.setStyle(Paint.Style.FILL);
        heartPaint.setColor(warningColor);

        // 波形画笔
        wavePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        wavePaint.setStyle(Paint.Style.STROKE);
        wavePaint.setStrokeWidth(4f);
        wavePaint.setColor(Color.WHITE);

        heartPath = new Path();
        wavePath = new Path();
        arcRect = new RectF();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;

        float padding = 20f;
        radius = Math.min(width, height) * 0.4f;
        centerX = width / 2f;
        centerY = height / 2f;

        // 弧形区域
        float arcRadius = radius * 0.9f;
        arcRect.set(
                centerX - arcRadius,
                centerY - arcRadius,
                centerX + arcRadius,
                centerY + arcRadius
        );

        // 构建心形路径
        buildHeartPath();

        // 构建心电图路径
//        buildWaveformPath();
    }

    private void buildHeartPath() {
        float heartSize = radius * 0.25f;
        heartPath.reset();

        // 心形绘制
        heartPath.moveTo(centerX, centerY + heartSize * 0.4f);

        // 左侧曲线
        heartPath.cubicTo(
                centerX - heartSize * 0.5f, centerY - heartSize * 0.2f,
                centerX - heartSize * 0.9f, centerY - heartSize * 0.5f,
                centerX - heartSize * 0.35f, centerY - heartSize * 0.6f
        );

        // 顶部曲线
        heartPath.cubicTo(
                centerX, centerY - heartSize * 0.9f,
                centerX + heartSize * 0.35f, centerY - heartSize * 0.6f,
                centerX + heartSize * 0.35f, centerY - heartSize * 0.6f
        );

        // 右侧曲线
        heartPath.cubicTo(
                centerX + heartSize * 0.9f, centerY - heartSize * 0.5f,
                centerX + heartSize * 0.5f, centerY - heartSize * 0.2f,
                centerX, centerY + heartSize * 0.4f
        );

        heartPath.close();
    }

    private void buildWaveformPath() {
        float waveHeight = radius * 0.15f;
        float startX = centerX - radius * 0.15f;
        float startY = centerY;

        wavePath.reset();
        wavePath.moveTo(startX, startY);

        // 绘制心电图波形
        wavePath.lineTo(startX + radius * 0.1f, startY - waveHeight * 0.5f);
        wavePath.lineTo(startX + radius * 0.15f, startY + waveHeight * 0.3f);
        wavePath.lineTo(startX + radius * 0.2f, startY - waveHeight * 0.4f);
        wavePath.lineTo(startX + radius * 0.25f, startY);
        wavePath.lineTo(startX + radius * 0.3f, startY - waveHeight);
        wavePath.lineTo(startX + radius * 0.35f, startY + waveHeight * 0.6f);
        wavePath.lineTo(startX + radius * 0.4f, startY - waveHeight * 0.3f);
        wavePath.lineTo(startX + radius * 0.45f, startY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制背景弧线
        canvas.drawCircle(centerX, centerY, radius * 0.9f, backgroundPaint);

        // 2. 计算彩色彩色区域
        float criticalPosition = sweepAngle * criticalThreshold / maxValue;

        // 3. 绘制正常区域（蓝色）
        coloredArcPaint.setColor(normalColor);
        canvas.drawArc(arcRect, startAngle, criticalPosition, false, coloredArcPaint);

        // 4. 绘制警告区域（红色）
        coloredArcPaint.setColor(warningColor);
        canvas.drawArc(arcRect, startAngle + criticalPosition, sweepAngle - criticalPosition, false, coloredArcPaint);

        // 5. 绘制刻度线和刻度值
        drawScales(canvas);

        // 6. 绘制心形图标
        canvas.drawPath(heartPath, heartPaint);

        // 7. 绘制心电图波形
        canvas.drawPath(wavePath, wavePaint);

        // 8. 绘制主数值
        drawValue(canvas);
    }

    private void drawScales(Canvas canvas) {
        // 绘制长刻度线和值
        for (int i = 0; i < scales.length; i++) {
            float value = scales[i];
            float angle = startAngle + (sweepAngle * value / maxValue);
            float angleRad = (float) Math.toRadians(angle);

            // 计算位置
            float scaleLength = 25f;
            float startX = (float) (centerX + radius * Math.cos(angleRad));
            float startY = (float) (centerY + radius * Math.sin(angleRad));
            float endX = (float) (centerX + (radius - scaleLength) * Math.cos(angleRad));
            float endY = (float) (centerY + (radius - scaleLength) * Math.sin(angleRad));

            // 绘制刻度线
            canvas.drawLine(startX, startY, endX, endY, scalePaint);

            // 绘制刻度值
            float textRadius = radius - scaleLength - 15f;
            float textX = (float) (centerX + textRadius * Math.cos(angleRad));
            float textY = (float) (centerY + textRadius * Math.sin(angleRad)) + 10;

            canvas.drawText(String.valueOf((int) value), textX, textY, textPaint);
        }

//        // 绘制短刻度线（较小刻度）
//        int minorScaleCount = 36;
//        for (int i = 0; i < minorScaleCount; i++) {
//            float value = maxValue * i / minorScaleCount;
//            boolean skip = false;
//
//            // 跳过已有刻度的位置
//            for (int scale : scales) {
//                if (Math.abs(value - scale) < 0.5f) {
//                    skip = true;
//                    break;
//                }
//            }
//            if (skip) continue;
//
//            float angle = startAngle + (sweepAngle * value / maxValue);
//            float angleRad = (float) Math.toRadians(angle);
//
//            // 计算位置
//            float scaleLength = 12f;
//            float startX = (float) (centerX + radius * Math.cos(angleRad));
//            float startY = (float) (centerY + radius * Math.sin(angleRad));
//            float endX = (float) (centerX + (radius - scaleLength) * Math.cos(angleRad));
//            float endY = (float) (centerY + (radius - scaleLength) * Math.sin(angleRad));
//
//            // 绘制刻度线
//            canvas.drawLine(startX, startY, endX, endY, scalePaint);
//        }
    }

    private void drawValue(Canvas canvas) {
        // 绘制标题
        float titleY = centerY - radius * 0.1f;
        canvas.drawText(title, centerX, titleY, textPaint);

        // 绘制主数值
        String valueText = String.format("%.0f", currentValue);
        canvas.drawText(valueText, centerX, centerY + 30, valuePaint);

        // 绘制单位
        canvas.drawText(unit, centerX, centerY + 60, textPaint);
    }

    // 设置当前值（带动画）
    public void setValue(float value, boolean animate) {
        if (value > maxValue) value = maxValue;
        if (value < 0) value = 0;

        if (animate) {
            ValueAnimator animator = ValueAnimator.ofFloat(currentValue, value);
            animator.setDuration(1200);
            animator.setInterpolator(new AccelerateDecelerateInterpolator());
            animator.addUpdateListener(animation -> {
                currentValue = (float) animation.getAnimatedValue();
                invalidate();
            });
            animator.start();
        } else {
            currentValue = value;
            invalidate();
        }
    }

    public void setTitle(String title) {
        this.title = title;
        invalidate();
    }

    public void setUnit(String unit) {
        this.unit = unit;
        invalidate();
    }

    public void setCriticalThreshold(int threshold) {
        this.criticalThreshold = threshold;
        invalidate();
    }

    public void setNormalColor(int color) {
        this.normalColor = color;
        invalidate();
    }

    public void setWarningColor(int color) {
        this.warningColor = color;
        invalidate();
    }

    public void setScales(int[] scales) {
        this.scales = scales;
        invalidate();
    }

}
